package com.demo.task;

import com.alibaba.druid.util.StringUtils;
import com.demo.common.model.TbTask;
import com.demo.common.model.TbWeekReport;
import com.demo.util.DateUtils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 本 demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法
 * 详见 JFinal 俱乐部: http://jfinal.com/club
 * 
 * BlogService
 * 所有 sql 与业务逻辑写在 Service 中，不要放在 Model 中，更不
 * 要放在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */
public class TaskService {
	
	/**
	 * 所有的 dao 对象也放在 Service 中，并且声明为 private，避免 sql 满天飞
	 * sql 只放在业务层，或者放在外部 sql 模板，用模板引擎管理：
	 * 			http://www.jfinal.com/doc/5-13
	 */
	private TbTask dao = new TbTask().dao();
	
	public Page<TbTask> paginate(int pageNumber, int pageSize, String condition,List<Object> paramValue) {
		return dao.paginate(pageNumber, pageSize, "select * ",
				"FROM tb_task WHERE 1=1 " + condition + " order by reportDate desc,weight DESC", paramValue.toArray());
	}
	
	public TbTask findById(int id) {
		return dao.findById(id);
	}
	
	public void deleteById(int id) {
		dao.deleteById(id);
	}

	public List<TbTask> getAll(){
		return dao.findAll();
	}

	public List<Record> statistics(Map map) {
		String startTimeQuery = (String) map.get("startTime");
		String endTimeQuery = (String) map.get("endTime");
		Boolean complete = (Boolean) map.get("complete");
		String sql = "select COUNT(*) as taskDoingCount ,userName,userId from tb_task WHERE complete=? GROUP BY userName,userId";
		if(!StringUtils.isEmpty(startTimeQuery)){
			sql = sql + " and reportDate>='" + startTimeQuery + "'";
		}
		if(!StringUtils.isEmpty(endTimeQuery)){
			sql = sql + " and reportDate<='" + endTimeQuery + "'";
		}

		List<Record> list = Db.find(sql,complete);
		List<Record> returnList = new ArrayList<>(list.size());

		Date now = new Date();
		for (Record record : list) {
			Integer userId = record.getInt("userId");
			if (userId == null){
				continue;
			}
			String sql1 = "select * from tb_task where complete=0 AND userId=?";
			if(!StringUtils.isEmpty(startTimeQuery)){
				sql1 = sql1 + " and reportDate>='" + startTimeQuery + "'";
			}
			if(!StringUtils.isEmpty(endTimeQuery)){
				sql1 = sql1 + " and reportDate<='" + endTimeQuery + "'";
			}
			List<Record> tasks = Db.find(sql1, userId);
			record.set("tasks",tasks);
			for (Record tbTask : tasks) {
				int daysDate = 0;
				Date endTime = tbTask.getDate("endTime");
				Date startTime = tbTask.getDate("startTime");
				daysDate = DateUtils.getDaysDate(startTime, now);
				tbTask.set("duringTime",daysDate);
			}

			returnList.add(record);
		}
		return returnList;
	}
}
